package com.zhdl.modules.prefiresys.service.impl;

import com.project.common.service.impl.BaseServiceImpl;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import com.zhdl.modules.prefiresys.entity.DetectorAreaInfo;
import com.zhdl.modules.prefiresys.entity.QDetectorAreaInfo;
import com.zhdl.modules.prefiresys.repository.DetectorAreaInfoRepository;
import com.zhdl.modules.prefiresys.service.DetectorAreaInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;


@Slf4j
@Service
public class DetectorAreaInfoServiceImpl extends BaseServiceImpl<String, DetectorAreaInfo, DetectorAreaInfoRepository> implements DetectorAreaInfoService {


    @Override
    public List<DetectorAreaInfo> findAllNoBy(){
          return repository.findAll();
    }

    /**
     * 通过防区编号 更新防区信息
     *
     * @param detectorId 探测器ID
     * @param areaName   防区名称
     * @param areaNo     防区编号
     * @param status     防区状态 0 未启用 1 启用
     * @return
     */
    @Override
    @Transactional
    public int updateAreaByNo(String detectorId, byte areaNo, String areaName, boolean status) {
        return repository.updateAreaByNo(detectorId, areaNo, areaName, status);
    }

    /**
     * 删除 探测器信息
     *
     * @param detectorId 探测器Id
     * @return 状态码 1
     */
    @Override
    public int deleteByDetectorId(String detectorId) {
        return repository.deleteByDetectorId(detectorId);
    }

    /**
     * 列表查看防区详情信息
     *
     * @param detectorIds 探测器ID
     * @return
     */
    @Override
    public List<DetectorAreaInfo> findListByDetIds(List<String> detectorIds) {
        // 基本查询
        QDetectorAreaInfo detectorAreaInfo = QDetectorAreaInfo.detectorAreaInfo;
        JPAQuery<DetectorAreaInfo> query = jpaQueryFactory()
                .selectFrom(detectorAreaInfo);
        BooleanBuilder builder = new BooleanBuilder();

        if (detectorIds.size() > 0) {
            BooleanBuilder builder1 = new BooleanBuilder();
            for (String id : detectorIds)
                builder1.or(detectorAreaInfo.detectorId.eq(id));

            builder.and(builder1);
        }
        List<DetectorAreaInfo> fetch = query.where(builder)
                .orderBy(detectorAreaInfo.areaName.desc())
                .fetch();
        return fetch;
    }

    /**
     * 通过探测器id和防区编号 查询详情信息
     *
     * @param detectorId
     * @param areaNo
     * @return
     */
    @Override
    public DetectorAreaInfo findByAreaNo(String detectorId, byte areaNo) {
        // 基本查询
        QDetectorAreaInfo detectorAreaInfo = QDetectorAreaInfo.detectorAreaInfo;
        DetectorAreaInfo detEntity = jpaQueryFactory().selectFrom(detectorAreaInfo)
                .where(
                        detectorAreaInfo.detectorId.eq(detectorId),
                        detectorAreaInfo.areaNo.eq(areaNo))
                .fetchFirst();
        return detEntity;
    }
}
